package com.yunxi.service.dubboService.impl.sto;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.yunxi.core.enums.DMSEnumsEntity;
import com.yunxi.core.web.DictConstant;
import com.yunxi.model.order.OrderCustomer;
import com.yunxi.model.order.PmsVehicleStock;
import com.yunxi.model.sto.VehicleOffline;
import com.yunxi.order.service.OrderActualSalesDubboService;
import com.yunxi.service.localService.OrderCustomerService;
import com.yunxi.service.localService.sto.VehicleMaintainRecordService;
import com.yunxi.service.localService.sto.VehicleOfflineService;
import com.yunxi.service.localService.sto.VehicleStockMService;
import com.yunxi.sto.pojo.*;
import com.yunxi.sto.service.StoStockInPlanDubboService;
import com.yunxi.sto.service.StoStockOutPlanDubboService;
import com.yunxi.sto.service.VehicleStockDubboService;
import com.yunxi.vehicle.pojo.VehicleCatalogListVO;
import com.yunxi.vehicle.pojo.VehicleSeriesListVO;
import com.yunxi.vip.pojo.StoVehicleExpVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 经销商车辆库存 服务实现类
 * </p>
 *
 * @author caoYong
 * @since 2019-05-29
 */
public class VehicleStockDubboServiceImpl implements VehicleStockDubboService {

    private static final Logger logger = LoggerFactory.getLogger(VehicleStockDubboServiceImpl.class);

    @Autowired
    @Qualifier(value = "vehicleStockMServiceImpl")
    VehicleStockMService vehicleStockService;

    @Autowired
    @Qualifier(value = "stoStockInPlanDubboServiceImpl")
    StoStockInPlanDubboService stoStockInPlanDubboService;

    @Autowired
    @Qualifier(value = "stoStockOutPlanDubboServiceImpl")
    StoStockOutPlanDubboService stoStockOutPlanDubboService;

    @Autowired
    @Qualifier(value = "vehicleMaintainRecordServiceImpl")
    VehicleMaintainRecordService vehicleMaintainRecordService;

    @Autowired
    @Qualifier(value = "vehicleOfflineServiceImpl")
    VehicleOfflineService vehicleOfflineService;

    @Autowired
    @Qualifier(value = "orderCustomerServiceImpl")
    OrderCustomerService orderCustomerService;


    @Override
    public VehicleStockVO getById(String id) {
        PmsVehicleStock vehicleStock = vehicleStockService.getById(id);
        VehicleStockVO vehicleStockVO = new VehicleStockVO();
        BeanUtils.copyProperties(vehicleStock, vehicleStockVO);
        return vehicleStockVO;
    }

    @Override
    public void saveOrUpdate(VehicleStockVO vehicleStockVO) {
        //每次保养之前都将记录存储到保养记录表
        vehicleMaintainRecordService.saveRecord(vehicleStockVO);

        //每次保养的操作都将预计保养时间刷新
        SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.DATE, 15);
        Date nextDate = cal.getTime();
        PmsVehicleStock vehicleStock = new PmsVehicleStock();
        //上次保养时间
        vehicleStockVO.setStartDate(sdf.format(new Date()));
        //预计保养时间
        vehicleStockVO.setMaintainDate(sdf.format(nextDate));
        if(StringUtils.isEmpty(vehicleStockVO.getPartnerCode())){
            vehicleStockVO.setPartnerCode(null);
        }
        BeanUtils.copyProperties(vehicleStockVO, vehicleStock);
        vehicleStockService.saveOrUpdate(vehicleStock);
    }

    @Override
    public void removeById(String id) {
    vehicleStockService.removeById(id);
    }

    @Override
    public PageInfo<VehicleStockQueryVO> findPageByVO(VehicleStockQueryVO vehicleStockQueryVO, Integer pageNum, Integer pageSize) {
        String customPackCodeStr = vehicleStockQueryVO.getCustomPackCodeStr();
        if(StringUtil.isNotEmpty(customPackCodeStr)){
            String[] split = customPackCodeStr.split(",");
            List<String> strings = Arrays.asList(split);
            vehicleStockQueryVO.setCustomPackCodeList(strings);
//            vehiclePackageDubboService.queryVehiclePackageByList()
        }
        logger.debug("=======================车辆库存查询b:"+vehicleStockQueryVO.getPartnerCode()+"===========");
        PageInfo<VehicleStockQueryVO> pageInfo = vehicleStockService.pageByVo(vehicleStockQueryVO, pageNum, pageSize);
        List<VehicleStockQueryVO> list = pageInfo.getList();
        getPackName(list);
        return pageInfo;
    }

    @Override
    public List<VehicleStockQueryVO> export(VehicleStockQueryVO vehicleStockQueryVO) throws Exception {
        List<VehicleStockQueryVO> list = vehicleStockService.export(vehicleStockQueryVO);
        getPackName(list);
        return list;
    }

    /**
     * 根据选装包代码查询选装包名称
     * @param list
     */
    private void getPackName(List<VehicleStockQueryVO> list) {
        if (list != null && list.size() > 0) {
            for (VehicleStockQueryVO vo : list) {
                String customPackCode = vo.getCustomPackCode();
                if (StringUtil.isNotEmpty(customPackCode)) {
                    String[] split = customPackCode.split(",");
                    List<String> strings = Arrays.asList(split);
                    String s = vehicleStockService.queryVehiclePackageByList(strings);
                    vo.setCustomPackNameStr(s);
                }
            }
        }
    }

    @Override
    public void removeByListVo(List<VehicleStockVO> vehicleStockVOList) throws IllegalAccessException, InvocationTargetException, InstantiationException {
        vehicleStockService.removeByListVo(vehicleStockVOList);
    }

    /**
     * 车辆冻结
     * @param list l
     */
    @Override
    public void frozenAndReset(List<VehicleStockFrozenVO> list,String isFrozen,Integer frozenReasonKey,String userId) throws Exception{
        vehicleStockService.frozen(list,isFrozen,frozenReasonKey,userId);
    }

    /**
     * 维修出入库
     * @param list l
     * @throws Exception e
     */
    @Override
    public void repairInOut(List<String> list,Integer isRepairOut) throws Exception {
//        vehicleStockService.repairInOut(list,isRepairOut);
        if(list != null && list.size() > 0){
            for(String id : list){
                PmsVehicleStock pmsVehicleStock = vehicleStockService.getById(id);
                if(pmsVehicleStock != null){
                    //维修出库
                    if(isRepairOut == 1){
                        StoStockOutPlanVO stoStockOutPlanVO = new StoStockOutPlanVO();
                        stoStockOutPlanVO.setVin(pmsVehicleStock.getVin());
                        stoStockOutPlanVO.setStorageCode(pmsVehicleStock.getStorageLocation());
                        stoStockOutPlanVO.setStockOutType("12");//送修出库
                        stoStockOutPlanDubboService.saveOrUpdate(stoStockOutPlanVO);
                    }
                    //维修入库
                    else if(isRepairOut == 0){
                        StoStockInPlanVO stoStockInPlanVO = new StoStockInPlanVO();
                        stoStockInPlanVO.setVin(pmsVehicleStock.getVin());
                        stoStockInPlanVO.setStockInType("4");//送修入库
                        stoStockInPlanDubboService.saveAndUpdate(stoStockInPlanVO);
                    }
                }
                else{
                    throw new Exception("操作失败,无法根据主键id"+id+"找到对应库存记录!");
                }
            }
        }
        else {
            throw new Exception("操作失败,主键id集合为空!");
        }
    }

    /**
     *点击库存列表根据vehicleId查看厂端车辆详情
     * @param vehicleId
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @Override
    public VehicleStockVO findByVehicleId(String vehicleId) throws InvocationTargetException, IllegalAccessException {

        return vehicleStockService.findByVehicleId(vehicleId);
    }

    @Override
    public PageInfo<VehicleStockQueryVO> findMaintainPageByVO(VehicleStockQueryVO vehicleStockQueryVO, Integer pageNum, Integer pageSize) throws InvocationTargetException, IllegalAccessException {

        PageInfo<VehicleStockQueryVO> pageInfo = vehicleStockService.maintainPageByVo(vehicleStockQueryVO, pageNum, pageSize);

        return pageInfo;
    }

    @Override
    public List<VehicleStockQueryVO> findMaintainList(VehicleStockQueryVO vehicleStockQueryVO) throws InvocationTargetException, IllegalAccessException {

        List<VehicleStockQueryVO> list = vehicleStockService.maintainList(vehicleStockQueryVO);

        return list;
    }

    @Override
    public List<VehicleStockMaintainVO> mainTainExport(VehicleStockQueryVO vehicleStockQueryVO) throws InvocationTargetException, IllegalAccessException {
        return vehicleStockService.mainTainExport(vehicleStockQueryVO);
    }

    @Override
    public List<VehicleSeriesListVO> seriesList() throws Exception {
        return vehicleStockService.seriesList();
    }

    @Override
    public List<VehicleCatalogListVO> catalogList() throws Exception {
        return vehicleStockService.catalogList();
    }

    /**
     * 导入批量冻结/解冻
     * @param vehicleStockImportVO
     * @throws Exception
     */
    @Override
    public void importFrozen(VehicleStockImportVO vehicleStockImportVO, String updateBy) throws Exception {
        List<String> vinList = vehicleStockImportVO.getVinList();
        Integer isFrozen = vehicleStockImportVO.getIsFrozen();//1冻结,0解冻
        if(isFrozen == null) throw new Exception("操作失败,参数isFrozen不能为空!");
        if(vinList == null || vinList.size() <= 0) throw new Exception("操作失败,导入内容为空!");
        List<VehicleStockFrozenVO> list = new ArrayList<>();
        for(String vin : vinList){
            QueryWrapper<PmsVehicleStock> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("VIN",vin);
            PmsVehicleStock vehicleStock = vehicleStockService.getOne(queryWrapper);
            if(vehicleStock == null) throw new Exception("操作失败,VIN码:"+vin+"不存在!");
            VehicleStockFrozenVO vo = new VehicleStockFrozenVO();
            vo.setBusinessKey(vehicleStock.getVehicleId());
            list.add(vo);
        }
        vehicleStockService.frozen(list,isFrozen.toString(),null,updateBy);
    }

    /**
     * 体验车查询
     * @param vehicleStockQueryVO
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo<VehicleStockQueryVO> sharePage(VehicleStockQueryVO vehicleStockQueryVO, Integer pageNum, Integer pageSize) throws Exception {
        return vehicleStockService.sharePage(vehicleStockQueryVO,pageNum,pageSize);
    }

    /**
     * 体验车管理
     * @param vehicleStockQueryVO
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo<VehicleStockQueryVO> newSharePage(VehicleStockQueryVO vehicleStockQueryVO, Integer pageNum, Integer pageSize) throws Exception {
        return vehicleStockService.newSharePage(vehicleStockQueryVO,pageNum,pageSize);
    }

    /**
     * 畅想车分页
     * @param vehicleStockQueryVO
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo<VehicleStockQueryVO> financePage(VehicleStockQueryVO vehicleStockQueryVO, Integer pageNum, Integer pageSize) throws Exception {
        String partnerCode = vehicleStockQueryVO.getPartnerCode();
        //根据partnerCode查询是渠道还是金融机构
        if(StringUtils.isNotEmpty(partnerCode)){
            String partnerType = vehicleStockService.queryPartnerType(partnerCode);
            if(StringUtils.isNotEmpty(partnerType) && partnerType.equals("SELL")){
                vehicleStockQueryVO.setPartnerType(0);//渠道商
            }
            else if (StringUtils.isNotEmpty(partnerType) && partnerType.equals("010")){
                vehicleStockQueryVO.setPartnerType(1);//金融机构
            }
        }
        return vehicleStockService.financePage(vehicleStockQueryVO,pageNum,pageSize);
    }

    /**
     * 共享车查询
     * @param vehicleStockQueryVO
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @Override
    public PageInfo<VehicleStockQueryVO> shareList(VehicleStockQueryVO vehicleStockQueryVO, Integer pageNum, Integer pageSize) throws Exception {
        return vehicleStockService.shareList(vehicleStockQueryVO,pageNum,pageSize);
    }


    /**
     * 设置共享车
     * @param list
     * @param userCode
     * @param isAdd 是否新增,1新增,0取消
     * @throws Exception
     */
    @Override
    public void setShare(List<String> list, String userCode, Integer isAdd) throws Exception {
        for (String id : list){
            PmsVehicleStock vehicleStock = vehicleStockService.getById(id);
            if(vehicleStock == null) throw new Exception("操作失败,无法根据id:"+id+"找到对应记录!");
            QueryWrapper<VehicleOffline> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("VIN",vehicleStock.getVin());
            VehicleOffline vehicleOffline = vehicleOfflineService.getOne(queryWrapper);
            if(vehicleOffline == null) throw new Exception("操作失败,VIN码:"+vehicleStock.getVin()+"不存在下线记录!");
            vehicleOffline.setIsShare(isAdd);
            //限制体验车,畅享车不能被添加为共享车
            //INVE 国内商品车;EXVE 海外商品车 OFFLINE
            checkVehicleType(vehicleStock, vehicleOffline);
            vehicleOfflineService.saveOrUpdate(vehicleOffline);
        }
    }

    /**
     * 限制仅商品车才能添加为共享车
     * @param vehicleStock
     * @param vehicleOffline
     * @throws Exception
     */
    private void checkVehicleType(PmsVehicleStock vehicleStock, VehicleOffline vehicleOffline) throws Exception {
        String carType = vehicleOffline.getCarType();
        if(StringUtils.isEmpty(carType) || (!carType.equals("INVE") && ! carType.equals("EXVE"))){
            throw new Exception("操作失败,只能添加商品车为共享车!");
        }
        QueryWrapper<OrderCustomer> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("VIN",vehicleStock.getVin());
        List<OrderCustomer> list1 = orderCustomerService.list(queryWrapper1);
        if(list1 != null && list1.size() > 0){
            OrderCustomer orderCustomer = list1.get(0);
            Integer buyType = orderCustomer.getBuyType();
            if(buyType != null && (buyType.equals(2) || buyType.equals(3)) ){
                throw new Exception("操作失败,体验车或畅享车不能添加为共享车!");
            }
        }
    }

    /**
     * 取消共享车
     * @param vin
     * @throws Exception
     */
    @Override
    public void cancelShare(String vin) throws Exception {
        QueryWrapper<VehicleOffline> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("VIN",vin);
        VehicleOffline vehicleOffline = vehicleOfflineService.getOne(queryWrapper);
        if(vehicleOffline == null)throw new Exception("操作失败,VIN码:"+vin+"不存在下线记录!");
        vehicleOffline.setIsShare(0);
        vehicleOfflineService.saveOrUpdate(vehicleOffline);
    }

    @Override
    public void putVehicle(StoVehicleExpVO stoVehicleExpVO , int hireStatus) {

        //根据vin查询批售中当前对应的零售订单号

        //根据零售订单号查询订单信息

        if(hireStatus==DMSEnumsEntity.HireStatus.UP.getCode()){

        }else{

        }
        //查找最新的订单，没有归还的数据

        //如果为上架 设置起租时间


        //如果为下架 设置退还时间


        //更新订单信息


        //更新车辆状态
        vehicleOfflineService.putVehicle("",hireStatus);
    }

    /**
     * 导出车辆冻结明细
     * @return
     * @throws Exception
     */
    @Override
    public List<VehicleStockFrozenListVO> exportFrozenList() throws Exception {
        return vehicleStockService.exportFrozenList();
    }

    /**
     * 库存报表
     * @param vehicleStockReportVO
     * @return
     */
    @Override
    public List<VehicleStockReportVO> stockReport(VehicleStockReportVO vehicleStockReportVO)throws Exception {
        String beginDate = vehicleStockReportVO.getBeginDate();
        String endDate = vehicleStockReportVO.getEndDate();
        List<String> dateList = getDateList(beginDate, endDate);
        vehicleStockReportVO.setDateList(dateList);
        List<VehicleStockReportVO> list = vehicleStockService.stockReport(vehicleStockReportVO);
        return list;
    }


    /**
     * 库存报表详情
     * @param vehicleStockReportDetailVO
     * @return
     * @throws Exception
     */
    @Override
    public List<VehicleStockReportDetailVO> stockReportDetail(VehicleStockReportDetailVO vehicleStockReportDetailVO) throws Exception {
        String beginDate = vehicleStockReportDetailVO.getBeginDate();
        String endDate = vehicleStockReportDetailVO.getEndDate();
        List<String> dateList = getDateList(beginDate, endDate);
        vehicleStockReportDetailVO.setDateList(dateList);
        List<VehicleStockReportDetailVO> list = vehicleStockService.stockReportDetail(vehicleStockReportDetailVO);
        return list;
    }

    /**
     * 绑定体验车
     * @param vehicleStockBindVO
     * @throws Exception
     */
    @Override
    public void vehicleBind(VehicleStockBindVO vehicleStockBindVO) throws Exception {
        String vin = vehicleStockBindVO.getVin();
        Integer bindState = vehicleStockBindVO.getBindState();
        if(StringUtils.isEmpty(vin) || bindState == null){
            throw new Exception("操作失败,车辆VIN码或绑定状态为空!");
        }
        QueryWrapper<VehicleOffline> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("VIN",vin);
        VehicleOffline vehicleOffline = vehicleOfflineService.getOne(queryWrapper);
        if(vehicleOffline == null)throw new Exception("操作失败,VIN码:"+vin+"不存在!");
        vehicleOffline.setStorageStatus(bindState);
        vehicleOfflineService.saveOrUpdate(vehicleOffline);

        QueryWrapper<PmsVehicleStock> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("VIN",vin);
        PmsVehicleStock vehicleStock = vehicleStockService.getOne(queryWrapper1);
        if(vehicleStock != null){
            vehicleStock.setStorageStatus(bindState);
            vehicleStockService.saveOrUpdate(vehicleStock);
        }
    }

    /**
     * 试驾车出库
     * @param vehicleStockBindVO
     * @throws Exception
     */
    @Override
    public void testDriveOut(VehicleStockBindVO vehicleStockBindVO) throws Exception {
        String vin = vehicleStockBindVO.getVin();
        QueryWrapper<PmsVehicleStock> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("VIN",vin);
        PmsVehicleStock vehicleStock = vehicleStockService.getOne(queryWrapper);
        if(vehicleStock == null)throw new Exception("操作失败,无法根据VIN:"+vin+"找到对应库存记录!");
        vehicleStock.setStorageCode(null);
        vehicleStock.setStorageLocation(null);
        vehicleStock.setOutStockDate(new Date());
        vehicleStock.setStorageStatus(2);
        vehicleStockService.saveOrUpdate(vehicleStock);

        QueryWrapper<VehicleOffline> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("VIN",vin);
        VehicleOffline vehicleOffline = vehicleOfflineService.getOne(queryWrapper1);
        if(vehicleOffline == null)throw new Exception("操作失败,无法根据VIN:"+vin+"找到对应下线记录!");
        vehicleOffline.setStorageStatus(2);
        vehicleOffline.setCarState(DictConstant.VEHICLE_TURN_STATE_15LSCK);
        vehicleOfflineService.saveOrUpdate(vehicleOffline);

    }

    /**
     * 组装查询日期集合
     * @param beginDate
     * @param endDate
     * @return
     * @throws Exception
     */
    private List<String> getDateList(String beginDate, String endDate) throws Exception {
        if(StringUtils.isEmpty(beginDate) || StringUtils.isEmpty(endDate)){
            throw new Exception("操作失败,起至查询日期不能为空!");
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date begin = simpleDateFormat.parse(beginDate);
            Date end = simpleDateFormat.parse(endDate);
            if(begin.after(end)){
                throw new Exception("操作失败,查询日期起不能大于查询日期止!");
            }
            long diffDays = (end.getTime()-begin.getTime())/1000/24/60/60;//日期相隔天数
            List<String> dateList = new ArrayList<>();
            dateList.add(beginDate);
            for(int i = 1; i<=diffDays;i++){
                Calendar instance = Calendar.getInstance();
                instance.setTime(begin);
                instance.add(Calendar.DATE,i);
                Date time = instance.getTime();
                dateList.add(simpleDateFormat.format(time));
            }
            return dateList;
        }
        catch (ParseException e){
            throw new Exception("操作失败,日期格式需要为yyyy-MM-dd!");
        }

    }
}
